import Plan from '@/models/Plan.model';
import { PaginatedResult } from '@/types';
import { getPaginationParams } from '@/utils/helpers';
import logger from '@/utils/logger';

interface CreatePlanData {
  name: string;
  code: string;
  description?: string;
  price: number;
  billingCycleCode: string;
  priceMonthly: number;
  priceYearly: number;
  maxUsers?: number;
  maxStorage?: number;
  maxProjects?: number;
  supportLevel: string;
  hasApiAccess?: boolean;
  hasCustomDomain?: boolean;
  hasWhiteLabel?: boolean;
  hasSso?: boolean;
  hasAdvancedAnalytics?: boolean;
  sortOrder?: number;
}

interface UpdatePlanData {
  name?: string;
  code?: string;
  description?: string;
  price?: number;
  billingCycleCode?: string;
  priceMonthly?: number;
  priceYearly?: number;
  maxUsers?: number;
  maxStorage?: number;
  maxProjects?: number;
  supportLevel?: string;
  hasApiAccess?: boolean;
  hasCustomDomain?: boolean;
  hasWhiteLabel?: boolean;
  hasSso?: boolean;
  hasAdvancedAnalytics?: boolean;
  isActive?: boolean;
  sortOrder?: number;
}

/**
 * 套餐服务
 */
export class PlanService {
  /**
   * 创建套餐
   */
  async createPlan(data: CreatePlanData): Promise<Plan> {
    const plan = await Plan.create({
      ...data,
      isActive: true,
      sortOrder: data.sortOrder || 0,
    });

    logger.info(`创建套餐成功: ${plan.name} (${plan.id})`);

    return plan;
  }

  /**
   * 获取套餐详情
   */
  async getPlanById(id: string): Promise<Plan | null> {
    return Plan.findByPk(id);
  }

  /**
   * 获取所有套餐
   */
  async listPlans(page: number = 1, pageSize: number = 20): Promise<PaginatedResult<Plan>> {
    const pagination = getPaginationParams(page, pageSize);

    const { count, rows } = await Plan.findAndCountAll({
      offset: pagination.offset,
      limit: pagination.limit,
      order: [['sortOrder', 'ASC'], ['createdAt', 'DESC']],
    });

    return {
      data: rows,
      pagination: {
        total: count,
        page: pagination.page,
        pageSize: pagination.pageSize,
        totalPages: Math.ceil(count / pagination.pageSize),
      },
    };
  }

  /**
   * 获取激活的套餐
   */
  async listActivePlans(): Promise<Plan[]> {
    return Plan.findAll({
      where: { isActive: true },
      order: [['sortOrder', 'ASC']],
    });
  }

  /**
   * 更新套餐
   */
  async updatePlan(id: string, data: UpdatePlanData): Promise<Plan> {
    const plan = await Plan.findByPk(id);

    if (!plan) {
      throw new Error('套餐不存在');
    }

    await plan.update(data);

    logger.info(`更新套餐: ${plan.name} (${plan.id})`);

    return plan;
  }

  /**
   * 删除套餐
   */
  async deletePlan(id: string): Promise<void> {
    const plan = await Plan.findByPk(id);

    if (!plan) {
      throw new Error('套餐不存在');
    }

    // 检查是否有租户使用此套餐
    const Tenant = (await import('@/models/Tenant.model')).default;
    const tenantCount = await Tenant.count({ where: { planId: id } });
    if (tenantCount > 0) {
      throw new Error('无法删除：仍有租户使用此套餐');
    }

    await plan.destroy();

    logger.info(`删除套餐: ${plan.name} (${plan.id})`);
  }

  /**
   * 检查套餐资源限制
   */
  async checkResourceLimit(
    planId: string,
    resourceType: 'users' | 'storage' | 'projects',
    currentValue: number,
  ): Promise<{ allowed: boolean; limit: number | null; current: number }> {
    const plan = await Plan.findByPk(planId);

    if (!plan) {
      throw new Error('套餐不存在');
    }

    let limit: number | null = null;
    
    switch (resourceType) {
      case 'users':
        limit = plan.maxUsers || null;
        break;
      case 'storage':
        limit = plan.maxStorage || null;
        break;
      case 'projects':
        limit = plan.maxProjects || null;
        break;
    }

    return {
      allowed: limit === null || currentValue < limit,
      limit,
      current: currentValue,
    };
  }
  
  /**
   * 检查套餐功能权限
   */
  async checkFeatureAccess(
    planId: string,
    featureName: 'apiAccess' | 'customDomain' | 'whiteLabel' | 'sso' | 'advancedAnalytics',
  ): Promise<boolean> {
    const plan = await Plan.findByPk(planId);

    if (!plan) {
      throw new Error('套餐不存在');
    }

    switch (featureName) {
      case 'apiAccess':
        return plan.hasApiAccess;
      case 'customDomain':
        return plan.hasCustomDomain;
      case 'whiteLabel':
        return plan.hasWhiteLabel;
      case 'sso':
        return plan.hasSso;
      case 'advancedAnalytics':
        return plan.hasAdvancedAnalytics;
      default:
        return false;
    }
  }
}

export default new PlanService();


